<template>
  <div class="textbook-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ route.query.category_name ? `${route.query.category_name}教材` : '教材市场' }}</span>
          <el-button type="primary" @click="$router.push('/publish')">
            <el-icon><Plus /></el-icon>
            发布教材
          </el-button>
        </div>
      </template>
      
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <!-- 分类筛选已移除 -->
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.status" placeholder="选择状态" clearable @change="loadTextbooks">
              <el-option label="在售" value="on_sale" />
              <el-option label="已售" value="sold" />
              <el-option label="下架" value="off_shelf" />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="filters.search"
              placeholder="搜索教材名称、作者或描述"
              @keyup.enter="loadTextbooks"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button @click="loadTextbooks">搜索</el-button>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>
      
      <!-- 教材列表 -->
      <div class="textbook-grid" v-loading="loading">
        <el-empty v-if="!loading && textbooks.length === 0" description="暂无教材" />
        <div
          v-for="textbook in textbooks"
          :key="textbook.id"
          class="textbook-item"
          @click="goToDetail(textbook.id)"
        >
          <div class="textbook-image">
            <el-image
              :src="getTextbookImage(textbook)"
              fit="cover"
              :lazy="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-tag :type="getConditionType(textbook.condition)" class="condition-tag">
              {{ getConditionText(textbook.condition) }}
            </el-tag>
          </div>
          <div class="textbook-info">
            <h3 class="textbook-title">{{ textbook.title }}</h3>
            <p class="textbook-author">{{ textbook.author }}</p>
            <p class="textbook-publisher">{{ textbook.publisher }}</p>
            <div class="textbook-meta">
              <span class="textbook-category">{{ textbook.category_name }}</span>
              <span class="textbook-seller">卖家: {{ textbook.seller_name }}</span>
            </div>
            <div class="textbook-price">
              <span class="price">¥{{ textbook.price }}</span>
              <span class="original-price" v-if="textbook.original_price">
                原价: ¥{{ textbook.original_price }}
              </span>
            </div>
            <div class="textbook-status">
              <el-tag :type="textbook.status === 'on_sale' ? 'success' : 'info'">
                {{ textbook.status === 'on_sale' ? '在售' : textbook.status === 'sold' ? '已售' : '下架' }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Plus, Search, Picture } from '@element-plus/icons-vue'
import { textbookApi } from '../api/textbook'
import mathTextbook from '@/assets/images/math_textbook.svg'
import englishTextbook from '@/assets/images/english_textbook.svg'
import computerTextbook from '@/assets/images/computer_textbook.svg'
import physicsTextbook from '@/assets/images/physics_textbook.svg'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const textbooks = ref([])
const filters = reactive({
  status: 'on_sale',
  search: '',
  category_id: null
})
const pagination = reactive({
  page: 1,
  pageSize: 12,
  total: 0
})



// 加载教材列表
const loadTextbooks = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      status: filters.status,
      search: filters.search
    }
    
    // 添加分类筛选参数
    if (filters.category_id) {
      params.category_id = filters.category_id
    }
    const response = await textbookApi.getTextbooks(params)
    if (response.success) {
      textbooks.value = response.data
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载教材失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取教材图片
const getTextbookImage = (textbook) => {
  // 接收完整的textbook对象而不仅仅是images数组
  if (textbook.images && textbook.images.length > 0) {
    return textbook.images[0]
  }
  // 根据教材类别显示默认图片
  if (textbook.category_name) {
    const categoryImages = {
      '数学': mathTextbook,
      '英语': englishTextbook,
      '计算机': computerTextbook,
      '物理': physicsTextbook
    }
    return categoryImages[textbook.category_name] || ''
  }
  return ''
}

// 获取成色类型
const getConditionType = (condition) => {
  const types = {
    'new': 'success',
    'like_new': 'info',
    'good': 'primary',
    'fair': 'warning',
    'poor': 'danger'
  }
  return types[condition] || 'primary'
}

// 获取成色文本
const getConditionText = (condition) => {
  const texts = {
    'new': '全新',
    'like_new': '九成新',
    'good': '八成新',
    'fair': '七成新',
    'poor': '六成新'
  }
  return texts[condition] || '未知'
}

// 跳转到详情
const goToDetail = (id) => {
  router.push(`/textbooks/${id}`)
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  loadTextbooks()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadTextbooks()
}

onMounted(() => {
  // 从路由参数中获取分类信息
  const categoryId = route.query.category_id
  if (categoryId) {
    filters.category_id = categoryId
  }
  loadTextbooks()
})
</script>

<style scoped>
.textbook-list {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.filter-bar {
  margin-bottom: 20px;
}

.textbook-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.textbook-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.textbook-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.textbook-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.textbook-image .el-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 30px;
}

.condition-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.textbook-info {
  padding: 15px;
}

.textbook-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.textbook-author,
.textbook-publisher {
  font-size: 14px;
  color: #909399;
  margin: 5px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.textbook-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin: 10px 0;
}

.textbook-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.original-price {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
}

.textbook-status {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
